package com.nescafe.nescafepromo.model;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.nescafe.nescafepromo.command.CommandType;

public class NPRequest {

	private CommandType commandType = null;
	private HttpServletRequest httpReq = null;
	private Map<String, String> params = new HashMap<String, String>();
	private boolean _hasError = false;

	public NPRequest(HttpServletRequest httpReq) {
		this.httpReq = httpReq;
		parseRequest();
	}

	public NPRequest(HttpServletRequest httpReq, CommandType commandType) {
		this.httpReq = httpReq;
		this.commandType = commandType;
		parseRequest();
	}

	private void parseRequest() {
		try {
			Enumeration<?> en = (Enumeration<?>) httpReq.getParameterNames();
			while (en.hasMoreElements()) {
				String paramName = (String) en.nextElement();
				String paramValue = httpReq.getParameter(paramName);
				if (paramName.equals("com")) {
					commandType = CommandType.parse(paramValue);
				} else {
					params.put(paramName, paramValue);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (commandType == null) {
				_hasError = true;
			}
		}
	}

	public CommandType getCommand() {
		return commandType;
	}

	public boolean hasError() {
		return _hasError;
	}

	public void addParam(String key, String value) {
		this.params.put(key, value);
	}

	public String getParam(String key) {
		return params.get(key);
	}

	public Map<String, String> getParams() {
		return params;
	}

}
